package com.ajieee.merge.runner.finance.proxy;

import cn.idev.excel.FastExcel;
import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.read.listener.ReadListener;
import com.ajieee.merge.entity.finance.po.EtfQuotePO;
import com.ajieee.merge.entity.finance.po.StockQuotePO;
import com.ajieee.merge.runner.finance.dto.StockQuoteExcelModel;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.client.RestClient;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ajieee
 * @date 2025-10-13
 */
@Component
@RequiredArgsConstructor
public class SzseProxy {

	private final RestClient restClient;

	public List<StockQuotePO> getSzseStockQuotes(LocalDate date) {
		String uriString = UriComponentsBuilder.fromUriString("https://www.szse.cn/api/report/ShowReport")
				.queryParam("SHOWTYPE", "xlsx")
				.queryParam("CATALOGID", "1815_stock_snapshot")
				.queryParam("TABKEY", "tab1")
				.queryParam("txtBeginDate", date)
				.queryParam("txtEndDate", date)
				.build().encode().toUriString();
		byte[] respBytes = restClient.get()
				.uri(uriString)
				.retrieve()
				.body(byte[].class);
		Assert.notNull(respBytes, "请求深圳股票行情错误");

		List<StockQuotePO> pos = new ArrayList<>();
		try (InputStream inputStream = new ByteArrayInputStream(respBytes)) {
			FastExcel.read(inputStream, StockQuoteExcelModel.class, new ReadListener<StockQuoteExcelModel>() {
				@Override
				public void invoke(StockQuoteExcelModel data, AnalysisContext context) {
					StockQuotePO po = new StockQuotePO();
					BeanUtils.copyProperties(data, po);
					pos.add(po);
				}

				@Override
				public void doAfterAllAnalysed(AnalysisContext context) {

				}
			}).doReadAll();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		return pos;
	}

	public List<EtfQuotePO> getEtfHistoryQuote(String fundCode) {

		return null;
	}
}
